package com.supreme.nettyapp.generalclient.mqttclient.handler;

import com.supreme.nettyapp.generalclient.mqttclient.props.MqttClientProps;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.mqtt.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@Component
public class MqttClientHandler extends SimpleChannelInboundHandler<MqttMessage> {

    @Resource
    private MqttClientProps mqttClientProps;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        MqttFixedHeader connectFixedHeader = new MqttFixedHeader(
                MqttMessageType.CONNECT,
                false,
                MqttQoS.AT_MOST_ONCE,
                false,
                0);
        MqttConnectVariableHeader connectVariableHeader = new MqttConnectVariableHeader(
                "MQTT",
                5,
                true,
                true,
                false,
                0,
                false,
                false,
                60,
                MqttProperties.NO_PROPERTIES);
        MqttConnectPayload connectPayload = new MqttConnectPayload(
                mqttClientProps.getClientId(),
                MqttProperties.NO_PROPERTIES,
                null,
                null,
                mqttClientProps.getUsername(),
                mqttClientProps.getPassword().getBytes());
        MqttConnectMessage connectMessage = new MqttConnectMessage(connectFixedHeader, connectVariableHeader, connectPayload);
        ctx.writeAndFlush(connectMessage);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MqttMessage msg) throws Exception {
        MqttFixedHeader mqttFixedHeader = msg.fixedHeader();
        if (Objects.nonNull(mqttFixedHeader)) {
            MqttMessageType mqttMessageType = mqttFixedHeader.messageType();
            switch (mqttMessageType) {
                case CONNACK:
                    this.handleConnAckMessage(ctx, (MqttConnAckMessage) msg);
                    break;

                case SUBACK:
                    this.handleSubAckMessage(ctx, (MqttSubAckMessage) msg);
                    break;

                case PINGREQ:
                    this.handlePingReqMessage(ctx, msg);
                    break;

                case PINGRESP:
                    this.handlePingRespMessage(ctx, msg);
                    break;

                case PUBLISH:
                    this.handlePublishMessage(ctx, (MqttPublishMessage) msg);
                    break;

                case PUBACK:
                    this.handlePublishAckMessage(ctx, (MqttPubAckMessage) msg);
                    break;
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    private void handleConnAckMessage(ChannelHandlerContext ctx, MqttConnAckMessage msg) {
        MqttConnAckVariableHeader connAckVariableHeader = msg.variableHeader();
        MqttProperties properties = connAckVariableHeader.properties();
    }

    private void handleSubAckMessage(ChannelHandlerContext ctx, MqttSubAckMessage msg) {

    }

    private void handlePingReqMessage(ChannelHandlerContext ctx, MqttMessage msg) {

    }

    private void handlePingRespMessage(ChannelHandlerContext ctx, MqttMessage msg) {

    }

    private void handlePublishMessage(ChannelHandlerContext ctx, MqttPublishMessage msg) {
        String topicName = msg.variableHeader().topicName();
        ByteBuf payload = msg.payload();
        byte[] bytes = new byte[payload.readableBytes()];
        payload.readBytes(bytes);
        String message = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("Received message from topic: " + topicName + ", content: " + message);
    }

    private void handlePublishAckMessage(ChannelHandlerContext ctx, MqttPubAckMessage msg) {
//        byte[] payload = new byte[msg.payload().readableBytes()];
//        msg.payload().getBytes(msg.payload().readerIndex(), payload);
//        String payloadContent = new String(payload, StandardCharsets.UTF_8);
//        System.out.println("payloadContent = " + payloadContent);
    }
}
